﻿using AutoMapper;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.DBUtility;
using H2.NET.Web.Pages.SMD.Dto;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.Helper;
using H2.NET.Web.Workflow.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace H2.NET.Web.Pages.SMD.AjaxTools
{
    /// <summary>
    /// Handler 的摘要说明
    /// </summary>
    public class Handler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            switch (AksRequest.GetString("action"))
            {
                case "ValidAddress":
                    ValidAddress(context);
                    break;
                case "search_city":
                    search_city(context);
                    break;
                case "search_store":
                    search_store(context);
                    break;
                case "search_dealer":
                    search_dealer(context);
                    break;
                case "get_store":
                    get_store(context);
                    break;
                case "get_smd_store":
                    get_smd_store(context);
                    break;
                case "get_store_by_dealer":
                    get_store_by_dealer(context);
                    break;
                case "get_device_by_dealer":
                    get_device_by_dealer(context);
                    break;
                case "get_deposit_by_dealer":
                    get_deposit_by_dealer(context);
                    break;
                case "set_store":
                    set_store(context);
                    break;
                case "save_store":
                    save_store(context);
                    break;
                case "save_changed_store":
                    save_changed_store(context);
                    break;
                case "save_changed_device":
                    save_changed_device(context);
                    break;
                case "save_changed_contract":
                    save_changed_contract(context);
                    break;
                case "get_change_store":
                    get_change_store(context);
                    break;
                case "delete_changed_store":
                    delete_changed_store(context);
                    break;
                case "delete_changed_contract":
                    delete_changed_contract(context);
                    break;
                case "delete_changed_device":
                    delete_changed_device(context);
                    break;
                case "get_smd_device":
                    get_smd_device(context);
                    break;
                case "get_smd_Contract":
                    get_smd_Contract(context);
                    break;
                case "authId_list":
                    get_authId_list(context);
                    break;
                case "get_province_city":
                    get_province_city(context);
                    break;
                case "get_authId":
                    get_authId(context);
                    break;
                case "get_task":
                    get_task(context);
                    break;
                case "search_mp":
                    search_mp(context);
                    break;
                case "same_fullsetsn":
                    ValidFullSetSN(context);
                    break;
                case "same_sapDeviceNo":
                    ValidSapDeviceNo(context);
                    break;
                case "validateStoreEapproveSN":
                    ValidStoreEapproveSN(context);
                    break;
                case "get_tips":
                    get_tips(context);
                    break;
                case "getFullSet":
                    GetFullSet(context);
                    break;
                case "getStepUName":
                    GetStepUName(context);
                    break;
                case "GetBusinessKey":
                    GetBusinessKey(context);
                    break;
                case "SearchBusinessKey":
                    SearchBusinessKey(context);
                    break;
                case "GetFullsetDeposit":
                    GetFullsetDeposit(context);
                    break;

                #region Add By Tony 20160606

                case "search_subdealer":
                    search_subdealer(context);
                    break;

                case "search_bmc":
                    search_bmc(context);
                    break;

                case "search_accountowner":
                    search_accountowner(context);
                    break;

                #endregion
            }
        }



        #region 获取分销商列表
        private void search_subdealer(HttpContext context)
        {
            var keywords = AksRequest.GetFormString("keywords");
            var pageNumber = AksRequest.GetFormInt("pageNumber");
            var pageSize = AksRequest.GetFormInt("pageSize");
            var taskid = AksRequest.GetFormString("taskid");
            var region = AksRequest.GetFormString("region");
            var province = AksRequest.GetFormString("province");
            var dealers = new List<DealerDto>();

            StringBuilder sb = new StringBuilder();
            sb.Append(" DealerCode is not null and ( parentid<>null or ownertype = 2 )");

            if (!string.IsNullOrEmpty(keywords))
            {
                sb.Append(string.Format("and (DealerCode like '%{0}%' ", keywords));
                sb.Append(string.Format("or Name like '%{0}%' ", keywords));
                sb.Append(string.Format("or Region like '%{0}%' ", keywords));
                sb.Append(string.Format("or Province like '%{0}%' ", keywords));
                sb.Append(string.Format("or CityName like '%{0}%' )", keywords));
            }

            var builder = new StringBuilder();
            builder.Append("SELECT TOP " + pageSize + " * FROM ( ");
            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY DealerID) AS RowNumber,* FROM t_smd_Dealer ");
            builder.Append("WHERE " + sb.ToString());
            builder.Append(") A WHERE RowNumber > " + pageSize + "*(" + pageNumber + "-1)");

            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            using (IDataReader reader = DbHelperSQL.ExecuteReader(builder.ToString()))
            {
                while (reader.Read())
                {
                    dealers.Add(Mapper.DynamicMap<DealerDto>(reader));
                }
            }

            var total = Utils.StrToInt(DbHelperSQL.GetSingle("select count(1) from t_smd_Dealer where " + sb.ToString()).ToString(), 0);
            var pageNum = total / pageSize + (total % pageSize == 0 ? 0 : 1);
            context.Response.ContentType = "text/json";
            context.Response.Write("{\"pageNum\": " + pageNum + ", \"data\": " + JsonConvert.SerializeObject(dealers) + "}");
        }

        #endregion

        #region 获取BMC列表
        private void search_bmc(HttpContext context)
        {
            var keywords = AksRequest.GetFormString("keywords");
            var pageNumber = AksRequest.GetFormInt("pageNumber");
            var pageSize = AksRequest.GetFormInt("pageSize");
            var taskid = AksRequest.GetFormString("taskid");
            var bmcs = new List<BMCDto>();

            StringBuilder sb = new StringBuilder();
            sb.Append(" BMCCode is not null ");

            if (!string.IsNullOrEmpty(keywords))
            {
                sb.Append(string.Format("and (BMCCode like '%{0}%' ", keywords));
                sb.Append(string.Format("or BMCName like '%{0}%' )", keywords));
            }

            var builder = new StringBuilder();
            builder.Append("SELECT TOP " + pageSize + " * FROM ( ");
            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY BMCId) AS RowNumber,* FROM t_smd_BMCInfo ");
            builder.Append("WHERE " + sb.ToString());
            builder.Append(") A WHERE RowNumber > " + pageSize + "*(" + pageNumber + "-1)");

            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            using (IDataReader reader = DbHelperSQL.ExecuteReader(builder.ToString()))
            {
                while (reader.Read())
                {
                    bmcs.Add(Mapper.DynamicMap<BMCDto>(reader));
                }
            }

            var total = Utils.StrToInt(DbHelperSQL.GetSingle("select count(1) from t_smd_BMCInfo where " + sb.ToString()).ToString(), 0);
            var pageNum = total / pageSize + (total % pageSize == 0 ? 0 : 1);
            context.Response.ContentType = "text/json";
            context.Response.Write("{\"pageNum\": " + pageNum + ", \"data\": " + JsonConvert.SerializeObject(bmcs) + "}");
        }
        #endregion

        #region 获取负责销售列表
        private void search_accountowner(HttpContext context)
        {
            var keywords = AksRequest.GetFormString("keywords");
            var pageNumber = AksRequest.GetFormInt("pageNumber");
            var pageSize = AksRequest.GetFormInt("pageSize");
            var taskid = AksRequest.GetFormString("taskid");
            var accounts = new List<AccountOwnerDto>();

            StringBuilder sb = new StringBuilder();
            sb.Append(" AccountId is not null ");

            if (!string.IsNullOrEmpty(keywords))
            {
                sb.Append(string.Format("and (AccountOwner like '%{0}%' ", keywords));
                sb.Append(string.Format("or AccountEmail like '%{0}%' ", keywords));
                sb.Append(string.Format("or WindowsId like '%{0}%' )", keywords));
            }

            var builder = new StringBuilder();
            builder.Append("SELECT TOP " + pageSize + " * FROM ( ");
            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY AccountId) AS RowNumber,* FROM t_smd_accountowner ");
            builder.Append("WHERE " + sb.ToString());
            builder.Append(") A WHERE RowNumber > " + pageSize + "*(" + pageNumber + "-1)");

            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            using (IDataReader reader = DbHelperSQL.ExecuteReader(builder.ToString()))
            {
                while (reader.Read())
                {
                    accounts.Add(Mapper.DynamicMap<AccountOwnerDto>(reader));
                }
            }

            var total = Utils.StrToInt(DbHelperSQL.GetSingle("select count(1) from t_smd_accountowner where " + sb.ToString()).ToString(), 0);
            var pageNum = total / pageSize + (total % pageSize == 0 ? 0 : 1);
            context.Response.ContentType = "text/json";
            context.Response.Write("{\"pageNum\": " + pageNum + ", \"data\": " + JsonConvert.SerializeObject(accounts) + "}");
        }
        #endregion

        #region 获取提示
        public void get_tips(HttpContext context)
        {
            var pagename = AksRequest.GetString("pagename");

            var list = new List<OperationTipsDto>();
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("oleDB");
            using (SqlDataReader reader = DbHelperSQL.ExecuteReader(
                "select * from t_OperationTips where pagename=@pagename",
                new SqlParameter("@pagename", pagename)))
            {
                while (reader.Read())
                {
                    list.Add(Mapper.DynamicMap<OperationTipsDto>(reader));
                }
            }
            context.Response.ContentType = "text/json";
            context.Response.Write(JsonConvert.SerializeObject(list));
        }
        #endregion

        #region 提示固定资产号是否相同
        private void ValidFullSetSN(HttpContext context)
        {
            var fullSetSN = AksRequest.GetFormString("fullSetSN");
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            var dt = (t_smd_Device._FullSetSN == fullSetSN).ListFirst<t_smd_Device>(Storage.Context3);

            var isRepeat = false;
            isRepeat = dt != null;
            context.Response.Write(isRepeat ? "1" : "0");
        }
        #endregion

        #region  提示Sap Document Number是否相同
        private void ValidSapDeviceNo(HttpContext context)
        {
            var sapDeviceNo = AksRequest.GetFormString("sapDeviceNo");
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            var dt = (t_smd_Deposit._SapDeviceNo == sapDeviceNo).ListFirst<t_smd_Deposit>(Storage.Context3);

            var isRepeat = false;
            isRepeat = dt != null;
            context.Response.Write(isRepeat ? "1" : "0");
        }
        #endregion

        #region 提示是否有相同流水号
        private void ValidStoreEapproveSN(HttpContext context)
        {
            var EapproveSN = AksRequest.GetFormString("EapproveSN");
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            var dt = (t_smd_Store._EapproveSN == EapproveSN).ListFirst<t_smd_Store>(Storage.Context3);

            var isRepeat = false;
            isRepeat = dt != null;
            context.Response.Write(isRepeat ? "1" : "0");

        }
        #endregion


        #region 提示地址是否相同
        private void ValidAddress(HttpContext context)
        {
            var province = AksRequest.GetString("address");
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            var dt = DbHelperSQL.Query("select count(1) from t_smd_Store where StoreAddress = @StoreAddress").Tables[0];

            var isRepeat = false;
            isRepeat = dt != null && dt.Rows.Count > 0;
            context.Response.Write(isRepeat ? "1" : "0");
        }
        #endregion

        #region 查询城市
        private void search_city(HttpContext context)
        {
            var province = AksRequest.GetString("province");
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            DataTable dt = DbHelperSQL.Query(
                "select * from [t_smd_Config] where parentID = (select configid from [t_smd_Config] where value = '" +
                province +
                "' and [level] = 2) order by seq asc").Tables[0];
            string result = string.Empty;
            foreach (DataRow row in dt.Rows)
            {
                result += row["name"] + ",";
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(result.Trim());
        }
        #endregion

        #region 保存门店主数据
        private void save_store(HttpContext context)
        {
            var result = string.Empty;

            result = "success";

            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }
        #endregion

        #region 批量处理门店

        private void get_store(HttpContext context)
        {
            var taskids = AksRequest.GetString("ids");
            var stores = (v_StoreMasterData._TaskId.In(taskids.Split(','))).List<v_StoreMasterData>();

            var excludeAuthId = new List<string>();
            foreach (var store in stores)
            {
                if (string.IsNullOrEmpty(store.AuthID)) //如果没有授权号，就给个建议的号码
                {
                    var storeTypeCode = StoreService.GetStoreTypeCode(store.StoreType);
                    store.AuthID = AuthIDService.GetNextNumber(store.ProvinceName, storeTypeCode, true, excludeAuthId);

                    //更新到数据库，前面一个store是视图，所以要重新获取一下table的数据
                    var smd = (t_StoreMasterData._ID == store.ID).ListFirst<t_StoreMasterData>(Storage.Context1);
                    smd.AuthID = store.AuthID;
                    Storage.Save(Storage.Context1, smd);
                }
                else
                {
                    excludeAuthId.Add(store.AuthID);
                }
            }

            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";

            Mapper.CreateMap<v_StoreMasterData, StoreMasterDataDto>();
            var list = Mapper.Map<List<v_StoreMasterData>, List<StoreMasterDataDto>>(stores.ToList());
            var perms = new GridData<StoreMasterDataDto>(list);
            var result = JsonConvert.SerializeObject(perms, iso);

            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }

        private void get_smd_store(HttpContext context)
        {
            var condition = AksRequest.GetFormString("condition");
            var cd = new List<Condition>();
            if (condition != "" && condition != "[]")
            {
                cd = JsonConvert.DeserializeObject<List<Condition>>(condition);
            }
            var page = AksRequest.GetFormInt("page", 1);
            var pageSize = AksRequest.GetFormInt("pagesize", 20);
            var storeName = AksRequest.GetFormString("sortname");
            var sortOrder = AksRequest.GetFormString("sortorder");
            var storeIds = AksRequest.GetQueryString("storeIds");
            var taskid = AksRequest.GetString("taskid");
            var orderBy = string.Empty;
            if (string.IsNullOrEmpty(storeName))
            {
                orderBy = " storeid desc ";
            }
            else
            {
                orderBy = " " + storeName + " " + sortOrder + " ";
            }

            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            var result =
                JsonConvert.SerializeObject(StoreService.SearchStoreDto(page, pageSize, orderBy, cd, storeIds, taskid),
                    iso);
            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }

        private void get_store_by_dealer(HttpContext context)
        {
            var dealerid = AksRequest.GetInt("dealerid", 0);
            var stores = StoreService.FindSmdByDealerId(dealerid);

            // 映射字段关系
            var map = Mapper.CreateMap<t_smd_Store, StoreDto>();
            map.ForMember(d => d.ID, opt => opt.MapFrom(s => s.StoreID));
            map.ForMember(d => d.Address, opt => opt.MapFrom(s => s.StoreAddress));
            map.ForMember(d => d.ContractPerson, opt => opt.MapFrom(s => s.ContactPerson));
            map.ForMember(d => d.Telephone, opt => opt.MapFrom(s => s.PhoneNumber));
            map.ForMember(d => d.StoreStatus, opt => opt.MapFrom(s => s.StoreStatus));

            var list = Mapper.Map<List<t_smd_Store>, List<StoreDto>>(stores);

            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            var result = JsonConvert.SerializeObject(list, iso);

            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }

        private void get_device_by_dealer(HttpContext context)
        {
            var dealerid = AksRequest.GetInt("dealerid", 0);
            var devicedeposit = DeviceService.FindNormalDeviceDepositByDealerId(dealerid);

            var map = Mapper.CreateMap<v_DeviceDeposit, DeviceDepositDto>();
            var list = Mapper.Map<List<v_DeviceDeposit>, List<DeviceDepositDto>>(devicedeposit);

            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            var result = JsonConvert.SerializeObject(list, iso);

            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }

        private void get_deposit_by_dealer(HttpContext context)
        {
            var dealerid = AksRequest.GetInt("dealerid", 0);

            var dealerdeposits = DepositService.FindByDealerIdAndStoreIds(dealerid, null);

            var map = Mapper.CreateMap<v_DealerDeposit, DealerDepositDto>();
            var list = Mapper.Map<List<v_DealerDeposit>, List<DealerDepositDto>>(dealerdeposits);

            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            var result = JsonConvert.SerializeObject(list, iso);

            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }

        private void get_smd_device(HttpContext context)
        {
            var condition = AksRequest.GetFormString("condition");
            var cd = new List<Condition>();
            if (condition != "" && condition != "[]")
            {
                cd = JsonConvert.DeserializeObject<List<Condition>>(condition);
            }
            var page = AksRequest.GetFormInt("page", 1);
            var pageSize = AksRequest.GetFormInt("pagesize", 20);
            var storeName = AksRequest.GetFormString("sortname");
            var sortOrder = AksRequest.GetFormString("sortorder");
            var devices = AksRequest.GetQueryString("devices");
            var orderBy = string.Empty;
            var taskid = AksRequest.GetString("taskid");
            if (string.IsNullOrEmpty(storeName))
            {
                orderBy = "storeid desc ";
            }
            else
            {
                orderBy = " " + storeName + " " + sortOrder + " ";
            }

            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            var result = JsonConvert.SerializeObject(StoreService.SearchDeviceDto(page, pageSize, orderBy, cd, devices, taskid), iso);
            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }

        private void get_smd_Contract(HttpContext context)
        {
            var condition = AksRequest.GetFormString("condition");
            var cd = new List<Condition>();
            if (condition != "" && condition != "[]")
            {
                cd = JsonConvert.DeserializeObject<List<Condition>>(condition);
            }

            var storeIds = AksRequest.GetQueryString("storeids");

            var page = AksRequest.GetFormInt("page", 1);
            var pageSize = AksRequest.GetFormInt("pagesize", 20);
            var storeName = AksRequest.GetFormString("sortname");
            var sortOrder = AksRequest.GetFormString("sortorder");
            var orderBy = string.Empty;
            var taskid = AksRequest.GetString("taskid");
            if (string.IsNullOrEmpty(storeName))
            {
                orderBy = " storeid desc ";
            }
            else
            {
                orderBy = " " + storeName + " " + sortOrder + " ";
            }

            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            var result = JsonConvert.SerializeObject(ContractService.SearchContractDto(page, pageSize, orderBy, cd, storeIds, taskid), iso);
            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }

        private void set_store(HttpContext context)
        {
            var result = "success";
            #region 不要
            /*
            Mapper.CreateMap<StoreMasterDataDto, t_StoreMasterData>();

            var json = AksRequest.GetFormString("data");
            if (!json.StartsWith("[")) json = "[" + json + "]";
            var stores = JsonConvert.DeserializeObject<List<StoreMasterDataDto>>(json);


            var option = AksRequest.GetString("option");
            var remark = AksRequest.GetString("remark");

            if (stores == null || stores.Count == 0)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("请至少勾选一个门店");
                return;
            }

            // 保存业务数据
            foreach (var storeMasterData in stores)
            {
                Storage.TransactionExecute(o =>
                {
                    try
                    {
                        #region MyRegion

                        var storeid = 0;
                        var deviceid = 0;
                        storeMasterData.AuthID = AuthIDService.GetNextNumber(storeMasterData.ProvinceName, storeMasterData.StoreType, false);

                        #region 引擎传值

                        var taskAPI = new TaskAPI(storeMasterData.TaskId);
                        taskAPI["ApproveResult"] = option;
                        taskAPI["TaskID"] = taskAPI.TaskID;
                        taskAPI["IsChannelManagerConfirm"] = option;

                        #endregion

                        #region 步骤记录

                        var user = context.Session["UserAPI"] as t_User;
                        var ass = new t_Assessment();
                        ass.Process = taskAPI.Process;
                        ass.Incident = taskAPI.Incident;
                        ass.Step = taskAPI.Step;
                        ass.UserName = taskAPI.UserName;
                        ass.UserFullName = taskAPI.UserFullName;
                        ass.AssignedToUserName = user.UserName;
                        ass.AssignedToUserFullName = user.UserFullName;
                        ass.Department = user.Department;
                        ass.StartTime = taskAPI.StartTime;
                        ass.Time = System.DateTime.Now;
                        ass.Opinion = option;
                        ass.OpinionText = remark;
                        ass.Opinion2 = "";
                        ass.OpinionText2 = "";
                        ass.Status = 1;

                        Storage.Save(Storage.Context1, ass);

                        #endregion

                        if (!taskAPI.Send())
                        {
                            o.Rollback();
                            result = "处理失败";
                        }
                        else
                        {
                            var step = option == "0" ? "Finish" : "AuthID Confirm";
                            var task = TaskHelper.GetTask(taskAPI.Process, storeMasterData.Incident.Value, step);

                            #region 数据更新

                            if (option == "0")
                            {
                                var model = Mapper.Map<StoreMasterDataDto, t_StoreMasterData>(storeMasterData);
                                var store = new t_smd_Store();
                                var device = new t_smd_Device();
                                StoreService.SaveStore(model, ref store, ref device);

                                if (model.IsEapprove == false)
                                {
                                    // 如果是手动添加的，并且存在授权号，更新主数据
                                    var smd_store = StoreService.GetSmdStoreByAuthID(store.AuthID);
                                    if (smd_store != null)
                                    {
                                        store.StoreID = smd_store.StoreID;
                                        store.EntityState._Loaded = true;
                                    }
                                    var smd_device = DeviceService.GetSmdDeviceByFullSetSN(model.DeviceFullSetSN);
                                    if (smd_device != null)
                                    {
                                        device.DeviceID = smd_device.DeviceID;
                                        device.EntityState._Loaded = true;
                                    }
                                }

                                Storage.Save(Storage.Context3, store);
                                device.StoreID = store.StoreID;
                                Storage.Save(Storage.Context3, device);

                                model.StoreId = storeid = store.StoreID;
                                model.DeviceId = deviceid = device.DeviceID;
                                step = model.Step = "Finish";

                                taskAPI["BlankVlue"] = store.StoreID;
                            }
                            #endregion

                            if (step == "Finish")
                            {
                                #region 启动收取保证金流程

                                var taskApi = new TaskAPI(H2.NET.Web.Workflow.Helper.TaskHelper.STORE_DEPOSIT_RECEIVE_TASKID);
                                var applicationNo =
                                    Util.GenerateSequence(
                                        ((object[])taskApi["PrefixNo"])[0].ToString() + "-" +
                                        System.DateTime.Now.ToString("yyMM"), "", 4);
                                taskApi["IsRenovation"] = "1";
                                taskApi["BlankVlue"] = storeid;
                                taskApi["ParentProcess"] = taskAPI.Process;
                                taskApi["ParentIncident"] = taskAPI.Incident;
                                taskApi["AutoBusinessKey"] = H2.NET.Web.Workflow.Helper.Constant.PROCESS_STORE;
                                taskApi.InitTask(user, applicationNo);
                                if (!string.IsNullOrEmpty(storeMasterData.ApplicationType))
                                {
                                    taskApi["DeviceId"] = deviceid;
                                    taskApi["IsDevice"] = "1";
                                    taskApi.Summary = "汇款底单上传 / " + TaskHelper.getSummary(taskAPI.Summary);
                                    taskApi["Deposit"] = storeMasterData.MachineDeposit.Value.ToString();
                                }
                                else
                                {
                                    taskApi["IsDevice"] = "0";
                                    taskApi.Summary = "履约保证金确认 / " + TaskHelper.getSummary(taskAPI.Summary);
                                }

                                var channel = storeMasterData.Channel == "多乐士" ? "DULUX" : "LEVIS";

                                taskApi["DealerID"] = DealerService.GetByCode(storeMasterData.DealerCode).DealerID;
                                taskApi["AuthID"] = storeMasterData.AuthID;
                                taskApi["StoreType"] = storeMasterData.StoreType;
                                taskApi["Channel"] = channel;

                                taskApi.SetDepositReceiveRecipient(storeMasterData.AreaName, storeMasterData.ProvinceName,
                                    channel.ToUpper());
                                ass = taskApi.InitAssessment(user);
                                Storage.Save(Storage.Context1, ass);

                                taskApi.Send();

                                (t_Assessment.process == taskApi.Process & t_Assessment.incident == 0 &
                                 t_Assessment.assignedToUserName == user.UserName).Edit<t_Assessment>(p =>
                                 {
                                     p.Incident = taskApi.Incident;
                                 });

                                #endregion
                            }
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Logging.GetLogger().Error(ex);
                        o.Rollback();
                        result = ex.Message;
                    }
                });
            }

            */

            #endregion
            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }

        #endregion

        #region 获取美萍号
        private void search_mp(HttpContext context)
        {
            var keywords = AksRequest.GetFormString("keywords");
            var pageNumber = AksRequest.GetFormInt("pageNumber");
            var pageSize = AksRequest.GetFormInt("pageSize");
            var mphs = new List<MeiPingDto>();
            var strwhere = " SerialNumber is not null ";
            if (!string.IsNullOrEmpty(keywords))
            {
                keywords = "%" + keywords + "%";

                strwhere += "and (SerialNumber like '" + keywords + "'";
                strwhere += " ) ";
            }

            var builder = new StringBuilder();
            builder.Append("SELECT TOP " + pageSize + " * FROM ( ");
            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY ID) AS RowNumber,* FROM t_smd_Meiping ");
            builder.Append("WHERE " + strwhere);
            builder.Append(") A WHERE RowNumber > " + pageSize + "*(" + pageNumber + "-1)");

            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            using (IDataReader reader = DbHelperSQL.ExecuteReader(builder.ToString()))
            {
                while (reader.Read())
                {
                    mphs.Add(Mapper.DynamicMap<MeiPingDto>(reader));
                }
            }

            var total = Utils.StrToInt(DbHelperSQL.GetSingle("select count(1) from t_smd_Meiping where " + strwhere).ToString(), 0);
            var pageNum = total / pageSize + (total % pageSize == 0 ? 0 : 1);
            context.Response.ContentType = "text/json";
            context.Response.Write("{\"pageNum\": " + pageNum + ", \"data\": " + JsonConvert.SerializeObject(mphs) + "}");

        }
        #endregion

        #region 获取门店列表
        private void search_store(HttpContext context)
        {
            var keywords = AksRequest.GetFormString("keywords");
            var pageNumber = AksRequest.GetFormInt("pageNumber");
            var pageSize = AksRequest.GetFormInt("pageSize");
            var taskid = AksRequest.GetFormString("taskid");
            var dealerID = AksRequest.GetFormString("dealerID");
            var restrictDealer = AksRequest.GetFormString("RestrictDealer");
            var stores = new List<StoreDto>();

            var strwhere = " DealerID is not null ";
            var AllRegion = AksRequest.GetFormString("allRegin");
            if (!string.IsNullOrEmpty(keywords))
            {
                keywords = "%" + keywords + "%";

                strwhere += "and (AuthID like '" + keywords + "'";
                strwhere += " or StoreName like '" + keywords + "'";
                strwhere += " or StoreAddress like '" + keywords + "'";
                if (AllRegion != "True")
                {
                    strwhere += " or Province like '" + keywords + "'";
                    strwhere += " or CityName like '" + keywords + "'";
                }
                strwhere += " ) ";
            }
            if (restrictDealer != "false" && dealerID != "" && dealerID != "0")
            {
                strwhere += " and DealerID = " + dealerID;
            }

            if (!string.IsNullOrEmpty(taskid))
            {
                var taskapi = new TaskAPI(taskid);
                var region = taskapi.GetVariableBySingleValue("Region");
                if (AllRegion != "True")
                {
                    if (!string.IsNullOrEmpty(region))
                    {
                        strwhere += " and region='" + region.Trim() + "'";
                    }
                    var province = taskapi.GetVariableBySingleValue("Province");
                    if (!string.IsNullOrEmpty(province))
                    {
                        strwhere += " and province='" + province.Trim() + "'";
                    }
                }
                var channel = taskapi.GetVariableBySingleValue("Channel");
                if (!string.IsNullOrEmpty(channel))
                {
                    var channel_cn = channel.Trim() == "DULUX" ? "多乐士" : "来威";
                    strwhere += " and channel='" + channel_cn + "'";
                }
            }

            var builder = new StringBuilder();
            builder.Append("SELECT TOP " + pageSize + " * FROM ( ");
            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY StoreID) AS RowNumber,* FROM t_smd_Store ");
            builder.Append("WHERE " + strwhere);
            builder.Append(") A WHERE RowNumber > " + pageSize + "*(" + pageNumber + "-1)");

            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            using (SqlDataReader reader = DbHelperSQL.ExecuteReader(builder.ToString()))
            {
                while (reader.Read())
                {
                    var storeDto = new StoreDto
                    {
                        ID = Utils.StrToInt(reader["StoreID"].ToString(), 0),
                        AuthID = reader["AuthID"].ToString(),
                        StoreName = reader["StoreName"].ToString(),
                        Address = reader["StoreAddress"].ToString()
                    };

                    stores.Add(storeDto);
                }
            }

            var total = Utils.StrToInt(DbHelperSQL.GetSingle("select count(1) from t_smd_Store where " + strwhere).ToString(), 0);
            var pageNum = total / pageSize + (total % pageSize == 0 ? 0 : 1);
            context.Response.ContentType = "text/json";
            context.Response.Write("{\"pageNum\": " + pageNum + ", \"data\": " + JsonConvert.SerializeObject(stores) + "}");
        }
        #endregion

        #region 获取经销商列表

        private void search_dealer(HttpContext context)
        {
            var keywords = AksRequest.GetFormString("keywords");
            var pageNumber = AksRequest.GetFormInt("pageNumber");
            var pageSize = AksRequest.GetFormInt("pageSize");
            var taskid = AksRequest.GetFormString("taskid");
            var region = AksRequest.GetFormString("region");
            var province = AksRequest.GetFormString("province");
            var dealers = new List<DealerDto>();
            var strwhere = " DealerCode is not null ";
            if (!string.IsNullOrEmpty(keywords))
            {
                keywords = "%" + keywords + "%";

                strwhere += " and (parentid is null or ownertype = 1 ) ";
                strwhere += "and (DealerCode like '" + keywords + "'";
                strwhere += " or Name like '" + keywords + "'";
                strwhere += " or Region like '" + keywords + "'";
                strwhere += " or Province like '" + keywords + "'";
                strwhere += " or CityName like '" + keywords + "'";
                strwhere += " ) ";
            }

            // 优先取流程变量中的值
            if (!string.IsNullOrEmpty(taskid))
            {
                var taskapi = new TaskAPI(taskid);
                var taskapi_region = taskapi.GetVariableBySingleValue("Region");
                if (!string.IsNullOrEmpty(taskapi_region))
                {
                    region = taskapi_region.Trim();
                }
                var taskapi_province = taskapi.GetVariableBySingleValue("Province");
                if (!string.IsNullOrEmpty(taskapi_province))
                {
                    province = taskapi_province.Trim();
                }
            }
            if (!string.IsNullOrEmpty(region))
            {
                strwhere += " and region='" + region.Trim() + "'";
            }
            if (!string.IsNullOrEmpty(province))
            {
                strwhere += " and province='" + province.Trim() + "'";
            }

            var builder = new StringBuilder();
            builder.Append("SELECT TOP " + pageSize + " * FROM ( ");
            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY DealerID) AS RowNumber,* FROM t_smd_Dealer ");
            builder.Append("WHERE " + strwhere);
            builder.Append(") A WHERE RowNumber > " + pageSize + "*(" + pageNumber + "-1)");

            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            using (IDataReader reader = DbHelperSQL.ExecuteReader(builder.ToString()))
            {
                while (reader.Read())
                {
                    dealers.Add(Mapper.DynamicMap<DealerDto>(reader));
                }
            }

            var total = Utils.StrToInt(DbHelperSQL.GetSingle("select count(1) from t_smd_Dealer where " + strwhere).ToString(), 0);
            var pageNum = total / pageSize + (total % pageSize == 0 ? 0 : 1);
            context.Response.ContentType = "text/json";
            context.Response.Write("{\"pageNum\": " + pageNum + ", \"data\": " + JsonConvert.SerializeObject(dealers) + "}");
        }

        #endregion

        #region 获取授权号列表
        private void get_authId_list(HttpContext context)
        {
            var result = string.Empty;

            var province = AksRequest.GetFormString("province");
            var storeType = AksRequest.GetFormString("storeType");

            if (!string.IsNullOrEmpty(province) && !string.IsNullOrEmpty(storeType))
            {
                DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
                using (IDataReader reader = DbHelperSQL.ExecuteReader(
                    "select * from t_smd_AuthID where Province=@Province and StoreType=@StoreType order by Sequence desc",
                    new SqlParameter("@Province", province),
                    new SqlParameter("@StoreType", storeType)))
                {
                    while (reader.Read())
                    {
                        var builder = new StringBuilder();
                        builder.Append("<tr>");
                        builder.Append("<td>" + reader.GetString(1) + "</td>");
                        builder.Append("<td>" + reader.GetString(2) + "</td>");
                        builder.Append("<td>" + reader.GetString(4) + "</td>");
                        builder.Append("</tr>");

                        result += builder.ToString();
                    }
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                result = "<tr><td colspan=\"5\" style=\"text-align:center;\">无数据显示</td></tr>";
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }
        #endregion

        #region 批量变更操作
        private void save_changed_store(HttpContext context)
        {
            try
            {
                // 获取本次修改的修改日志
                var user = context.Session["UserAPI"] as t_User;
                var json = AksRequest.GetFormString("data").Trim('[', ']');
                var new_store = JsonConvert.DeserializeObject<t_smd_Store>(json);
                var store = (t_smd_Store._StoreID == new_store.StoreID).ListFirst<t_smd_Store>(Storage.Context3);
                var changelogs = DataHelper<t_smd_Store>.GetChangeLogs(store, new_store,
                    new_store.GetChangeFields(), "StoreID", user.UserFullName, "", "BatchChangeStore");

                // 获取已存在的门店修改日志
                if (context.Session["StoreDataChangeLog"] == null)
                {
                    context.Session["StoreDataChangeLog"] = new List<t_StoreDataChangeLog>();
                }
                var sdc_logs = context.Session["StoreDataChangeLog"] as List<t_StoreDataChangeLog>;

                // 从已存在的日志记录中移除本次修改的门店
                if (sdc_logs.Select(t => t.DataID).Contains(new_store.StoreID.ToString()))
                {
                    sdc_logs.RemoveAll(log => log.DataID == new_store.StoreID.ToString());
                }

                // 将本次的修改日志保存
                if (changelogs != null && changelogs.Count > 0)
                {
                    sdc_logs.AddRange(changelogs);
                }
                context.Session["StoreDataChangeLog"] = sdc_logs;

                Mapper.CreateMap<t_StoreDataChangeLog, StoreDataChangeLogDto>();
                var list = Mapper.Map<List<t_StoreDataChangeLog>, List<StoreDataChangeLogDto>>(sdc_logs);
                var iso = new IsoDateTimeConverter();
                iso.DateTimeFormat = "yyyy-MM-dd";
                var result = JsonConvert.SerializeObject(list, iso);

                context.Response.ContentType = "text/json";
                context.Response.Write(result);
            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用ajaxtools方法save_changed_store出错：" + ex.ToString());
                context.Response.ContentType = "text/plain";
                context.Response.Write("error");
            }
        }
        private void save_changed_device(HttpContext context)
        {
            try
            {
                // 获取本次修改的修改日志
                var user = context.Session["UserAPI"] as t_User;
                var json = AksRequest.GetFormString("data").Trim('[', ']');
                var new_device = JsonConvert.DeserializeObject<t_smd_Device>(json);
                var device = (t_smd_Device._DeviceID == new_device.DeviceID).ListFirst<t_smd_Device>(Storage.Context3);
                var changelogs = DataHelper<t_smd_Device>.GetChangeLogs(device, new_device,
                    new_device.GetChangeFields(), "DeviceID", user.UserFullName, "", "BatchChangeDevice");

                // 获取已存在的门店修改日志
                if (context.Session["StoreDataChangeLog_Device"] == null)
                {
                    context.Session["StoreDataChangeLog_Device"] = new List<t_StoreDataChangeLog>();
                }
                var sdc_logs = context.Session["StoreDataChangeLog_Device"] as List<t_StoreDataChangeLog>;

                // 从已存在的日志记录中移除本次修改的门店
                if (sdc_logs.Select(t => t.DataID).Contains(new_device.DeviceID.ToString()))
                {
                    sdc_logs.RemoveAll(log => log.DataID == new_device.DeviceID.ToString());
                }

                // 将本次的修改日志保存
                if (changelogs != null && changelogs.Count > 0)
                {
                    sdc_logs.AddRange(changelogs);
                }
                context.Session["StoreDataChangeLog_Device"] = sdc_logs;

                Mapper.CreateMap<t_StoreDataChangeLog, StoreDataChangeLogDto>();
                var list = Mapper.Map<List<t_StoreDataChangeLog>, List<StoreDataChangeLogDto>>(sdc_logs);
                var iso = new IsoDateTimeConverter();
                iso.DateTimeFormat = "yyyy-MM-dd";
                var result = JsonConvert.SerializeObject(list, iso);

                context.Response.ContentType = "text/json";
                context.Response.Write(result);
            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用ajaxtools方法save_changed_store出错：" + ex.ToString());
                context.Response.ContentType = "text/plain";
                context.Response.Write("error");
            }
        }
        private void save_changed_contract(HttpContext context)
        {
            try
            {
                // 获取本次修改的修改日志
                var user = context.Session["UserAPI"] as t_User;
                var json = AksRequest.GetFormString("data").Trim('[', ']');


                var contractDto = JsonConvert.DeserializeObject<StoreContractDto>(json);


                // 获取已存在的门店修改日志
                if (context.Session["StoreDataChangeLog_Contract"] == null)
                {
                    context.Session["StoreDataChangeLog_Contract"] = new List<t_StoreDataChangeLog>();
                }

                var sdc_Storelogs = context.Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;




                // 获取已存在的设备合同修改日志
                if (context.Session["StoreDataChangeLog_DeviceContract"] == null)
                {
                    context.Session["StoreDataChangeLog_DeviceContract"] = new List<t_StoreDataChangeLog>();
                }

                var sdc_Devicelogs = context.Session["StoreDataChangeLog_DeviceContract"] as List<t_StoreDataChangeLog>;




                //序列化对象保存storeContract
                Mapper.CreateMap<ContractDto, t_smd_Contract>();
                var new_contract = Mapper.Map<ContractDto, t_smd_Contract>(contractDto.contract);
                Mapper.CreateMap<ContractCancelDto, t_smd_Contract_Cancel>();
                if (new_contract != null)
                {
                    var contractCancel = Mapper.Map<ContractCancelDto, t_smd_Contract_Cancel>(contractDto.contract.StoreCancel);
                    if (contractCancel != null)
                    {
                        Storage.Save(Storage.Context3, contractCancel);
                    }
                }
                foreach (var device in contractDto.devices)
                {
                    Mapper.CreateMap<ContractDeviceCancelDto, t_smd_ContractDevice_Cancel>();
                    var deviceCancel = Mapper.Map<ContractDeviceCancelDto, t_smd_ContractDevice_Cancel>(device.DeviceCancel);
                    if (deviceCancel != null)
                    {
                        deviceCancel.EntityState._FieldState.Remove("ContractDeviceCancelID");
                        deviceCancel.EntityState._Loaded = true;
                        Storage.Save(Storage.Context3, deviceCancel);
                    }
                }
                if (new_contract != null)
                {
                    var contract = (t_smd_Contract._ContractID == new_contract.ContractID).ListFirst<t_smd_Contract>(Storage.Context3);
                    var changelogs = DataHelper<t_smd_Contract>.GetChangeLogs(contract, new_contract,
                        new_contract.GetChangeFields(), "ContractID", user.UserFullName, "", "BatchChangeContract");


                    //移除日志
                    if (sdc_Storelogs.Select(t => t.DataID).Contains(new_contract.ContractID.ToString()))
                    {
                        sdc_Storelogs.RemoveAll(log => log.DataID == new_contract.ContractID.ToString());
                    }
                    // 将本次的修改日志保存
                    if (changelogs != null && changelogs.Count > 0)
                    {
                        sdc_Storelogs.AddRange(changelogs);
                    }


                    context.Session["StoreDataChangeLog_Contract"] = sdc_Storelogs;
                }

                List<t_StoreDataChangeLog> deviceChangelogs = new List<t_StoreDataChangeLog>();
                //序列化设备合同对象保存deviceContract
                foreach (ContractDeviceDto deviceDto in contractDto.devices)
                {
                    Mapper.CreateMap<ContractDeviceDto, t_smd_ContractDevice>();
                    var new_contractDevice = Mapper.Map<ContractDeviceDto, t_smd_ContractDevice>(deviceDto);

                    if (new_contractDevice != null && new_contractDevice.ContractDeviceID != 0)
                    {
                        var contractDevice = (t_smd_ContractDevice._StoreID == deviceDto.Storeid
                                            & t_smd_ContractDevice._ContractDeviceID == deviceDto.ContractDeviceID).ListFirst<t_smd_ContractDevice>(Storage.Context3);
                        deviceChangelogs.AddRange(DataHelper<t_smd_ContractDevice>.GetChangeLogs(contractDevice, new_contractDevice,
                        new_contractDevice.GetChangeFields(), "ContractDeviceID", user.UserFullName, "", "BatchChangeContractDevice"));

                        // 从已存在的日志记录中移除本次修改的门店

                        if (sdc_Devicelogs.Select(t => t.DataID).Contains(new_contractDevice.ContractDeviceID.ToString()))
                        {
                            sdc_Devicelogs.RemoveAll(log => log.DataID == new_contractDevice.ContractDeviceID.ToString());
                        }

                        if (deviceChangelogs != null && deviceChangelogs.Count > 0)
                            sdc_Devicelogs.AddRange(deviceChangelogs);

                    }



                }

                context.Session["StoreDataChangeLog_DeviceContract"] = sdc_Devicelogs;



                sdc_Storelogs.AddRange(sdc_Storelogs);
                Mapper.CreateMap<t_StoreDataChangeLog, StoreDataChangeLogDto>();
                var list = Mapper.Map<List<t_StoreDataChangeLog>, List<StoreDataChangeLogDto>>(sdc_Storelogs);
                var iso = new IsoDateTimeConverter();
                iso.DateTimeFormat = "yyyy-MM-dd";
                var result = JsonConvert.SerializeObject(list, iso);

                context.Response.ContentType = "text/json";
                context.Response.Write(result);
            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用ajaxtools方法save_changed_store出错：" + ex.ToString());
                context.Response.ContentType = "text/plain";
                context.Response.Write("error");
            }
        }
        private void get_change_store(HttpContext context)
        {
            var stores_update = context.Session["ChangedStores"] as List<t_smd_Store>;
            if (stores_update == null) stores_update = new List<t_smd_Store>();

            Mapper.CreateMap<t_smd_Store, SmdStoreDto>();
            var list = Mapper.Map<List<t_smd_Store>, List<SmdStoreDto>>(stores_update);
            var perms = new GridData<SmdStoreDto>(list);
            var iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            var result = JsonConvert.SerializeObject(perms, iso);

            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }
        private void delete_changed_store(HttpContext context)
        {
            var logs = context.Session["StoreDataChangeLog"] as List<t_StoreDataChangeLog>;
            var logIds = new List<int>();
            if (logs != null)
            {
                var id = AksRequest.GetFormString("id");
                logIds.AddRange(logs.Where(t => t.DataID == id).Select(t => t.LogID).ToList());
                logs.RemoveAll(log => log.DataID == id);
                context.Session["StoreDataChangeLog"] = logs;
                ChangeLogService.DeleteLogs(logs.Where(t => t.DataID == id).Select(t => t.LogID).ToList());
            }
            ChangeLogService.DeleteLogs(logIds);
            context.Response.ContentType = "text/plain";
            context.Response.Write("success");
        }


        private void delete_changed_contract(HttpContext context)
        {
            var logs = context.Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;
            var logDevices = context.Session["StoreDataChangeLog_DeviceContract"] as List<t_StoreDataChangeLog>;
            var logIds = new List<int>();
            if (logs != null)
            {
                var id = AksRequest.GetFormString("id");
                // 门店合同变更日志
                logIds.AddRange(logs.Where(t => t.DataID == id).Select(t => t.LogID).ToList());
                logs.RemoveAll(log => log.DataID == id);
                context.Session["StoreDataChangeLog_Contract"] = logs;
                var contract = (t_smd_Contract._ContractID == id).ListFirst<t_smd_Contract>(Storage.Context3);

                var devices = (t_smd_ContractDevice._StoreID == contract.StoreID).List<t_smd_ContractDevice>(Storage.Context3);
                foreach (var device in devices)
                {
                    // 设备合同变更日志
                    logIds.AddRange(logDevices.Where(t => t.DataID == device.ContractDeviceID.ToString()).Select(t => t.LogID).ToList());
                    logDevices.RemoveAll(log => log.DataID == device.ContractDeviceID.ToString());
                }

                ChangeLogService.DeleteLogs(logIds);
                context.Session["StoreDataChangeLog_DeviceContract"] = logDevices;
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write("success");
        }

        private void delete_changed_device(HttpContext context)
        {
            var logs = context.Session["StoreDataChangeLog_Device"] as List<t_StoreDataChangeLog>;
            var logIds = new List<int>();
            if (logs != null)
            {
                var id = AksRequest.GetFormString("id");
                logIds.AddRange(logs.Where(t => t.DataID == id).Select(t => t.LogID).ToList());
                logs.RemoveAll(log => log.DataID == id);
                context.Session["StoreDataChangeLog_Device"] = logs;
                ChangeLogService.DeleteLogs(logs.Where(t => t.DataID == id).Select(t => t.LogID).ToList());
            }
            ChangeLogService.DeleteLogs(logIds);
            context.Response.ContentType = "text/plain";
            context.Response.Write("success");
        }
        #endregion

        #region 地区级联筛选
        private void get_province_city(HttpContext context)
        {
            var type = AksRequest.GetFormString("type");
            var ar = AksRequest.GetFormString("val");
            var and = string.Empty;
            if (AksRequest.GetFormString("type") == "province")
            {
                and = " and [level] = 2 ";
            }
            var sql = "select * from [t_smd_Config] where parentID = (select configid from [t_smd_Config] where value = '" + ar + "') " + and + " order by seq asc";

            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            var province = DbHelperSQL.Query(sql).Tables[0];
            var result = "";
            if (province.Rows.Count > 0)
            {
                for (var i = 0; i < province.Rows.Count; i++)
                {
                    var rst = "";
                    rst += province.Rows[i]["Value"] + ",";
                    rst += province.Rows[i]["Name"] + ",";
                    result += rst + "|";
                }
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }
        #endregion

        private void get_authId(HttpContext context)
        {
            var authid = AksRequest.GetString("param");
            var store = (t_smd_Store._AuthID == authid).ListFirst<t_smd_Store>(Storage.Context3);
            if (store == null) context.Response.Write("{\"info\":\"验证通过！\",\"status\":\"y\"}");
            else context.Response.Write("{\"info\":\"授权号‘" + authid + "’已被‘" + store.StoreName + "’使用\",\"status\":\"n\"}");
        }

        private void get_task(HttpContext context)
        {
            var task = TaskHelper.GetTask(AksRequest.GetString("p"), AksRequest.GetInt("i", 0), AksRequest.GetString("s"));
            if (task == null)
                context.Response.Write("error");
            else
                context.Response.Write(task.strTaskId);

        }
        #region 获取业务流程号
        private void GetBusinessKey(HttpContext context)
        {
            var businesskey = AksRequest.GetString("businesskey");
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("bpmDB");
            var dt = DbHelperSQL.Query(BuildSqlStr(businesskey)).Tables[0];
            string json = JsonConvert.SerializeObject(dt).Replace(" ", "");
            context.Response.Write(json);
        }

        /// <summary>
        /// 根据keyword获取业务流程号提示
        /// </summary>
        /// <param name="context"></param>
        private void SearchBusinessKey(HttpContext context)
        {
            var businesskey = AksRequest.GetString("keyword");
            var sql = "select distinct businesskey as id,businesskey as name from " + DbHelperSQL.GetDatabaseName("oleDB") + ".dbo.t_smd_childprocess where businesskey like '%" + businesskey + "%'";
            var dt = DbHelperSQL.Query(sql);

            string json = JsonConvert.SerializeObject(dt).Replace("{\"ds\":", "");
            json = json.Substring(0, json.Length - 1);
            context.Response.Write(json);
        }

        /// <summary>
        /// 根据业务流程号来获取业务流程的相关子流程信息
        /// </summary>
        /// <param name="businesskey"></param>
        /// <returns></returns>
        public string BuildSqlStr(string businesskey, string fullsetsn = "")
        {

            //查找收件箱列表
            var sql = new System.Text.StringBuilder();
            sql.AppendLine(@"select A.*,case status1 when '1' then 'frm_inbox_late.gif' when '2' then 'frm_complete_complete.gif' when '4' then 'frm_inbox_aborted.gif' when '33' then 'frm_initiate_blank.gif' else '' end imgstatus, c.CacheValue stepcn,c1.CacheValue processcn,j.FULLNAME,convert(varchar(10),starttime,126) starttime1  from (select a.*,(case  when abortuser in ('magics11', '张佩华(Zhang Pei Hua)') then 'itss' else abortuser end) abortuser from (select top 50 [Priority],taskid,processname3,processname,
helpurl,openform,s.incident,steplabel,taskuser,assignedtouser,img_status,img_monitor,s.status,substatus,starttime,delaytime,overduetime,urgentduetime,summary,initiator,case when s.status1 = 33 and t.status = 'active' then '1' ELSE status1  end status1,initiator_name,taskuser_name,assignedtouser_name from (SELECT CASE ISNULL(ISNULL(p.DMO_Priority, p.Business_Priority), 3)
                                  WHEN 1 THEN 'Urgent'
                                  WHEN 2 THEN 'High'
                                  WHEN 3 THEN 'Routine'
                                END AS [Priority] ,
                                RTRIM(a.taskid) AS taskid ,");
            sql.AppendLine(" a.processname as processname3,");
            sql.AppendLine(" h.processname,");
            sql.AppendLine(@"RTRIM(a.helpurl) AS helpurl ,
                                '' AS openform ,
                                a.incident ,
                                a.steplabel ,
                                a.taskuser ,
                                a.assignedtouser ,
                                '' AS img_status ,
                                '' AS img_monitor ,
                                a.status ,
                                a.substatus ,
                                a.starttime ,
                                a.delaytime ,
                                a.overduetime ,
                                DATEDIFF(s, GETDATE(), a.urgentduetime) AS urgentduetime ,
                                c.summary ,
                                c.initiator ,
                                c.status status1,
                                '' AS initiator_name ,
                                '' AS taskuser_name ,
                                '' AS assignedtouser_name");
            sql.AppendLine(string.Format(@"FROM    tasks a with(nolock)
                                        LEFT JOIN {1}.dbo.mdc_Priority p ON a.PROCESSNAME = p.Process
                                                                                    AND p.Incident = a.INCIDENT
                                                                                    AND a.taskid NOT IN (
                                                                                    SELECT  taskid
                                                                                    FROM    taskqueue )
                                        INNER JOIN dbo.INITIATE  h WITH (NOLOCK) ON a.PROCESSNAME = h.PROCESSNAME
                                                                     AND H.PROCESSNAME IN (
                                                                     SELECT [PROCESSNAME]
                                                                     FROM   [PROCESSES]
                                                                     WHERE  [PROCESSES].[DESCRIPTION] IN (
                                                                            SELECT  KeyWords
                                                                            FROM    BPMSYSTEM
                                                                            WHERE   Platform = '{0}' ) )
                                        LEFT JOIN incidents c with(nolock) ON a.processname = c.processname
                                                                 AND a.incident = c.incident
                                WHERE   1 = 1", Util.AppSettings("platform"), DbHelperSQL.GetDatabaseName("oleDB")));
            sql.AppendLine(" and a.status = 1 ");

            sql.Append(")  as s join  (select DISTINCT Process,Incident,status from " + DbHelperSQL.GetDatabaseName("oleDB") + ".dbo.t_smd_ChildProcess a where a.BusinessKey = '" + businesskey + "' and status = 'active') T ON S.processname = t.Process and s.incident = t.incident" +
                          " order by taskid asc,s.incident asc ");

            sql.AppendLine(@" union all  select top 50 [Priority],taskid,processname3,processname,
helpurl,openform,s1.incident,steplabel,taskuser,assignedtouser,img_status,img_monitor,s1.status,substatus,starttime,delaytime,overduetime,urgentduetime,summary,initiator,case when s1.status1 = 33 and t1.status = 'finish' then '2' when  s1.status1 = 33 and t1.status = 'abort' then 4 ELSE status1  end status1,initiator_name,taskuser_name,assignedtouser_name from (SELECT CASE ISNULL(ISNULL(p.DMO_Priority, p.Business_Priority), 3)
                                  WHEN 1 THEN 'Urgent'
                                  WHEN 2 THEN 'High'
                                  WHEN 3 THEN 'Routine'
                                END AS [Priority] ,
                                RTRIM(a.taskid) AS taskid ,");

            sql.AppendLine(" a.processname as processname3,");
            sql.AppendLine(" h.processname,");
            sql.AppendLine(@"RTRIM(a.helpurl) AS helpurl ,
                                '' AS openform ,
                                a.incident ,
                                a.steplabel ,
                                a.taskuser ,
                                a.assignedtouser ,
                                '' AS img_status ,
                                '' AS img_monitor ,
                                a.status ,
                                a.substatus ,
                                a.starttime ,
                                a.delaytime ,
                                a.overduetime ,
                                DATEDIFF(s, GETDATE(), a.urgentduetime) AS urgentduetime ,
                                c.summary ,
                                c.initiator ,
                                c.status status1 ,
                                '' AS initiator_name ,
                                '' AS taskuser_name ,
                                '' AS assignedtouser_name");
            sql.AppendLine(string.Format(@"FROM    tasks a with(nolock)
                                        LEFT JOIN {1}.dbo.mdc_Priority p ON a.PROCESSNAME = p.Process
                                                                                    AND p.Incident = a.INCIDENT
                                                                                    AND a.taskid NOT IN (
                                                                                    SELECT  taskid
                                                                                    FROM    taskqueue )
                                        INNER JOIN dbo.INITIATE h WITH (NOLOCK) ON a.PROCESSNAME = h.PROCESSNAME
                                                                     AND H.PROCESSNAME IN (
                                                                     SELECT [PROCESSNAME]
                                                                     FROM   [PROCESSES]
                                                                     WHERE  [PROCESSES].[DESCRIPTION] IN (
                                                                            SELECT  KeyWords
                                                                            FROM    BPMSYSTEM
                                                                            WHERE   Platform = '{0}' ) )
                                        LEFT JOIN incidents c with(nolock) ON a.processname = c.processname
                                                                 AND a.incident = c.incident
                                WHERE   1 = 1", Util.AppSettings("platform"), DbHelperSQL.GetDatabaseName("oleDB")));
            sql.AppendLine(" and CHARINDEX('B', a.STEPID) > 0 ");

            sql.AppendLine(string.Format(")  as s1 join  (select DISTINCT Process,Incident,status from {0}.dbo.t_smd_ChildProcess a where a.BusinessKey = '" + businesskey + "' ) T1 ON S1.processname = t1.Process and s1.incident = t1.incident where t1.status = 'finish' or (s1.status1 = 4)" +
                          " order by taskid asc,s1.incident asc )as a left join {0}.dbo.t_smd_Childprocess cp on cp.incident = a.incident and cp.process = a.processname ) as a left join {0}.DBO.t_Cache c  on a.steplabel collate Chinese_PRC_CI_AI = c.CacheKey collate Chinese_PRC_CI_AI left join {0}.DBO.t_Cache c1  on a.processname collate Chinese_PRC_CI_AI = c1.CacheKey collate Chinese_PRC_CI_AI left join {1}.DBO.JOBS J  on a.TASKUSER collate Chinese_PRC_CI_AI = j.NAME collate Chinese_PRC_CI_AI",
                          DbHelperSQL.GetDatabaseName("oleDB"), DbHelperSQL.GetDatabaseName("bpmDB")));

            TaskDB.Log("", true, "调用 inboxStore.aspx 页面 BuildSqlStr 方法SQL：" + sql.ToString());
            return sql.ToString();
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region 获取全套固定资产号
        private void GetFullSet(HttpContext context)
        {
            var DeliveryType = AksRequest.GetString("DeliveryType");
            var FULLSETSN = DeliveryType == "STD" ? "RT" : DeliveryType == "DIR" ? "DRT" : "TT";
            FULLSETSN += DateTime.Now.Year;

            var device = (t_smd_Device._DeliveryType == DeliveryType & t_smd_Device._FullSetSN.Like("%" + FULLSETSN + "%")).ListFirst<t_smd_Device>(Storage.Context3, "FullSetSN desc");
            var fullSetSN = FULLSETSN;
            var strNumber = "";

            if (device != null)
            {
                var number = Utils.StrToInt(device.FullSetSN.Split('-')[1], 0);
                number += 1;
                if (number >= 0 && number < 10)
                {
                    strNumber = "00" + number;
                }
                else if (number >= 10 && number < 100)
                {
                    strNumber = "0" + number;
                }
                else if (number >= 100)
                {
                    strNumber = number.ToString();
                }
            }
            else
            {
                strNumber = "001";
            }
            context.Response.Write(fullSetSN + "-" + strNumber);

        }
        #endregion

        #region 获取itss 根据经销商编号,授权号,固定资产号来获取设备信息

        protected void GetFullsetDeposit(HttpContext context)
        {
            var dealercode = AksRequest.GetString("dealercode");
            var authid = AksRequest.GetString("authid");
            var fullsetsn = AksRequest.GetString("fullsetsn");

            var sql = string.Format("select distinct dl.dealercode,s.authid,d.fullsetsn,de.amount from {0}.dbo.t_smd_device d join {0}.dbo.t_smd_store s on d.storeid = s.storeid join {0}.dbo.t_smd_dealer dl on dl.dealerid = s.dealerid join {0}.dbo.t_smd_deposit de on de.storeid = s.storeid and de.deviceid = d.deviceid and de.dealerid = dl.dealerid where dl.dealercode = '" + dealercode + "' and d.fullsetsn = '" + fullsetsn + "' and s.authid='" + authid + "'", DbHelperSQL.GetDatabaseName("smdDB"));
            var dt = DbHelperSQL.Query(sql);
            string json = JsonConvert.SerializeObject(dt).Replace("{\"ds\":", "");

            sql = GetBusinessProcessByFullsetsn(fullsetsn);
            dt = DbHelperSQL.Query(sql);
            if (dt.Tables != null && dt.Tables.Count > 0 && dt.Tables[0].Rows.Count > 0)
            {
                var businessJson = JsonConvert.SerializeObject(dt).Replace("{\"ds\":", "");
                businessJson = (json.Length <= 3 ? "{" : ",") + "\"business\":" + businessJson.Substring(0, businessJson.Length - 1);
                json = json.Substring(0, json.Length <= 3 ? 1 : json.Length - 3) + businessJson + "}]}";
            }

            json = json.Substring(0, json.Length - 1);
            context.Response.Write(json);
        }

        protected string GetBusinessProcessByFullsetsn(string fullsetsn)
        {
            return string.Format("select max(taskid) taskid,businesskey,incident,summary from (select distinct t.taskid,c.businesskey,c.incident,ca.CacheValue process,rtrim(i.summary) summary,r.authid,r.DealerCode,FullsetSN from {1}.DBO.t_smd_childprocess c" +
                " join {1}.dbo.t_cache ca on ca.CacheKey = c.Process" +
                " join {1}.dbo.t_smd_relation r on c.businesskey = r.businesskey" +
                " join {2}.dbo.incidents i on i.processname = c.process and i.incident = c.incident and i.summary not like '%合同%'" +
                " join {2}.dbo.tasks t on t.processname = c.process and t.incident = c.incident" +
                " where c.status = 'active' and c.BusinessKey  is not null  and FullsetSN like '%{0}%' and fullsetsn not like '%D{0}%') a group by businesskey,incident,summary", fullsetsn, DbHelperSQL.GetDatabaseName("oleDB"), DbHelperSQL.GetDatabaseName("bpmDB"));
        }

        #endregion

        #region getStepUName
        protected void GetStepUName(HttpContext context)
        {
            var recA = new SortedList<string, string>();
            var storeid = AksRequest.GetFormString("storeid");
            var store = StoreService.GetSmdStoreById(Utils.StrToInt(storeid, 0));

            var json = "";

            var recS = (mdc_Recipient.process == "Store Deposit Receive" & mdc_Recipient.status == 1).List<mdc_Recipient>();
            foreach (var rec in recS)
            {
                if (string.IsNullOrEmpty(rec.Distribute)) continue;
                var distributes = rec.Distribute.Split('_');
                var regionA = distributes[0];
                var provinceA = distributes.Length > 1 ? distributes[1] : "*";
                var channelA = distributes.Length > 2 ? distributes[2] : "*";

                //判断区域
                if (!regionA.Contains("*") && !String.Equals(regionA, store.Region, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                //判断省份
                if (!provinceA.Contains("*") && !provinceA.Contains(store.Province))
                {
                    continue;
                }

                //判断渠道 DULUX LEVIS
                if (!channelA.Contains("*") && !String.Equals(channelA, store.Channel == "多乐士" ? "DULUX" : (store.Channel == "来威" ? "LEVIS" : "*"), StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                if (recA.ContainsKey(rec.Step))
                {
                    if (!recA.Values[recA.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                    {
                        recA[rec.Step] = recA.Values[recA.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") + rec.Recipient;
                    }
                }
                else
                {
                    recA.Add(rec.Step, rec.Recipient);
                }
            }

            var jsonStr = "";
            //步骤处理人赋值
            for (int i = 0; i < recA.Keys.Count; i++)
            {
                jsonStr += "\"R_" + recA.Keys[i].Replace(" ", "_") + "\":\"" + recA.Values[i].Replace(",", " ") + "\"";
                if (i < recA.Keys.Count - 1)
                {
                    jsonStr += ",";
                }
            }
            json = "{" + jsonStr + "}";

            context.Response.ContentType = "text/json";
            context.Response.Write(json);
        }
        #endregion
    }
}